package cn.qianxun.meta.word.replace;

import cn.hutool.core.util.StrUtil;
import cn.qianxun.meta.word.vo.GenerateManyMultTableVO;
import cn.qianxun.meta.word.vo.TableBodyData;
import cn.qianxun.meta.word.vo.TabularDataVO;
import com.aspose.words.*;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author fuzhilin
 * @Date 2021/12/2 0002 9:41
 * @Description
 */
public class ReplaceAndInsertMunltTable implements IReplacingCallback {
    private String key;
    private GenerateManyMultTableVO tableVO;

    public ReplaceAndInsertMunltTable(String key, GenerateManyMultTableVO tableVO) {
        this.key = key;
        this.tableVO = tableVO;
    }

    @Override
    public int replacing(ReplacingArgs e) throws Exception {
        //获取当前节点
        Node currentNode = e.getMatchNode();
        //节点拆分处理当前匹配字段
        splitRun(currentNode, e.getMatchOffset());
        //获取当前文档
        Document document = (Document) currentNode.getDocument();
        DocumentBuilder builder = new DocumentBuilder(document);
        //将光标移动到指定节点
        builder.moveTo(currentNode);
        // 添加表头并设置格式
        List<String> header = tableVO.getTitle();
        addTableHeader(builder, header);

        //设置表体的格式
        setTableBodyFormat(builder);
        // 根据集合循环添加数据行
        for (TabularDataVO collegeData : tableVO.getValues()) {
            addDataRow(builder, collegeData);
        }
        // 结束表格
        builder.endTable();
        //移动光标至末尾
        builder.moveToDocumentEnd();
        return ReplaceAction.SKIP;
    }

    /**
     * 添加数据行
     */
    private static void addDataRow(DocumentBuilder builder, TabularDataVO collegeData) throws Exception {
        //开始表格
        builder.insertCell();
        builder.write(collegeData.getFirstName());
        //垂直向下合并
        builder.getCellFormat().setVerticalMerge(CellMerge.FIRST);
        // 第二层循环开始循环添加每个组织下的下层组织
        for (int i = 0; i < collegeData.getTableBodyDataList().size(); i++) {
            //因为第一列要作为水平合并，所以判断
            if (i != 0) {
                builder.insertCell();
                builder.write("");
                builder.getCellFormat().setVerticalMerge(CellMerge.PREVIOUS);
            }
            //添加量表
            builder.insertCell();
            builder.write(StrUtil.emptyToDefault(collegeData.getTableBodyDataList().get(i).getName(), ""));
            builder.getCellFormat().setVerticalMerge(CellMerge.NONE);
            //添加数据
            List<String> data = collegeData.getTableBodyDataList().get(i).getData();
            for (String datum : data) {
                builder.insertCell();
                builder.write(String.valueOf(datum));
                builder.getCellFormat().setVerticalMerge(CellMerge.NONE);
            }
            builder.endRow();
        }
    }

    /**
     * 设置表体的格式
     */
    public static void setTableBodyFormat(DocumentBuilder builder) throws Exception {
        //清除格式
        builder.getCellFormat().clearFormatting();
        //设置单元格垂直
        builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
        //单元格背景颜色设置
        builder.getCellFormat().getShading().setBackgroundPatternColor(new Color(253, 253, 253, 255));
        //单元格边框颜色设置
        builder.getRowFormat().getBorders().setColor(new Color(1, 1, 1));
        //设置字体颜色
        builder.getFont().setColor(new Color(1, 1, 1));
        //这行代码禁用单元格中的文本自动换行功能
        builder.getCellFormat().setWrapText(false);
    }

    /**
     * 创建列
     *
     * @param value
     * @param doc
     * @return
     */
    static Cell createCell(String value, Document doc, boolean isHeader) {
        Cell c1 = new Cell(doc);
        Paragraph p = new Paragraph(doc);
        Run r = new Run(doc, value);
        r.getFont().setName("仿宋GB2312");
        r.getFont().setSize(14);
        if (isHeader) {
            r.getFont().setBold(true);
        } else {
            r.getFont().setBold(false);
        }
        p.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
        p.appendChild(r);
        c1.appendChild(p);
        return c1;
    }

    /**
     * 添加表头
     */
    private static void addTableHeader(DocumentBuilder builder, List<String> headers) throws Exception {
        //段落的对齐方式设置为居中对齐
        builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);/**居中***/
        //方法将清除单元格的所有格式设置，包括字体、颜色、边框等。如果您只想清除特定的格式设置，可以使用其他适当的方法，例如clearFormatting()方法的重载版本，该版本接受一个参数，用于指定要清除的格式设置类型。
        builder.getCellFormat().clearFormatting();
        //设置单元格的宽度  磅（points）。
        builder.getCellFormat().setWidth(70.0);
        //这只单元格的高度  磅（points）。
        builder.getRowFormat().setHeight(25.0);
        //设置单元格垂直
        builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
        //单元格背景颜色设置
        builder.getCellFormat().getShading().setBackgroundPatternColor(new Color(100, 150, 208));
        //单元格边框颜色设置
        builder.getRowFormat().getBorders().setColor(new Color(1, 1, 1));
        //设置字体颜色
        builder.getFont().setColor(new Color(255, 255, 255));
        //这行代码禁用单元格中的文本自动换行功能
        builder.getCellFormat().setWrapText(false);
        //这行代码启用单元格中文本的自动缩放以适应单元格大小。
        //builder.getCellFormat().setFitText(true);
        //这行代码设置行的高度规则为精确值。
        //builder.getRowFormat().setHeightRule(HeightRule.EXACTLY);
        //这行代码设置行的边框线样式为浮雕3D效果。
        //builder.getRowFormat().getBorders().setLineStyle(LineStyle.ENGRAVE_3_D);
        for (String header : headers) {
            builder.insertCell();
            builder.write(header);
        }
        builder.endRow();
    }

    /**
     * 替换参数位置
     *
     * @param currentNode
     * @param position
     */
    private void splitRun(Node currentNode, int position) {
        String text = currentNode.getText();
        Node newNode = currentNode.deepClone(true);
        if (text.length() >= position + this.key.length()) {
            ((Run) currentNode).setText(text.substring(position + this.key.length()));
        } else {
            int morlength = position + this.key.length() - text.length();
            ((Run) currentNode).setText("");
            Node tmpnode = currentNode;
            for (int i = 0; i < this.key.length(); i++) {
                System.out.println(i);
                tmpnode = tmpnode.getNextSibling();
                String tmptext = tmpnode.getText();
                System.out.println(tmptext);
                System.out.println(morlength);
                System.out.println("--------" + (tmptext.length() >= morlength));

                if (tmptext.length() >= morlength) {
                    ((Run) tmpnode).setText(tmptext.substring(morlength));
                    break;
                } else {
                    morlength = morlength - tmptext.length();
                    ((Run) tmpnode).setText("");
                }
            }
        }
        if (position > 0) {
            ((Run) newNode).setText(text.substring(0, position));
            currentNode.getParentNode().insertBefore(newNode, currentNode);
        }
    }

    public static void main(String[] args) throws Exception {
        GenerateManyMultTableVO tableVO = new GenerateManyMultTableVO();
        List<String> list = new ArrayList<>();
        list.add("项目");
        list.add("分类");
        list.add("人数");
        list.add("百分比");
        tableVO.setTitle(list);
        ArrayList<TabularDataVO> dataList = new ArrayList<>();
        TabularDataVO tabularDataVO1 = new TabularDataVO();
        tabularDataVO1.setFirstName("性别");
        ArrayList<TableBodyData> tableBodyDataList = new ArrayList<>();
        TableBodyData tableBodyData1 = new TableBodyData();
        TableBodyData tableBodyData2 = new TableBodyData();
        tableBodyData1.setName("男");
        tableBodyData2.setName("女");

        List<String> data1 = new ArrayList<>();
        data1.add("37,031");
        data1.add("51.64%");
        List<String> data2 = new ArrayList<>();
        data2.add("37,03");
        data2.add("51.6%");
        tableBodyData1.setData(data1);
        tableBodyData2.setData(data2);
        tableBodyDataList.add(tableBodyData1);
        tableBodyDataList.add(tableBodyData2);
        tabularDataVO1.setTableBodyDataList(tableBodyDataList);
        dataList.add(tabularDataVO1);

        //学段

        TabularDataVO tabularDataVO2 = new TabularDataVO();
        tabularDataVO2.setFirstName("学段");
        ArrayList<TableBodyData> tableBodyDataList1 = new ArrayList<>();
        TableBodyData tableBodyData3 = new TableBodyData();
        TableBodyData tableBodyData4 = new TableBodyData();
        tableBodyData3.setName("小学");
        tableBodyData4.setName("初中");

        List<String> data3 = new ArrayList<>();
        data3.add("37,031");
        data3.add("51.64%");
        List<String> data4 = new ArrayList<>();
        data4.add("37,03");
        data4.add("51.6%");
        tableBodyData3.setData(data3);
        tableBodyData4.setData(data4);
        tableBodyDataList1.add(tableBodyData3);
        tableBodyDataList1.add(tableBodyData4);
        tabularDataVO2.setTableBodyDataList(tableBodyDataList1);
        dataList.add(tabularDataVO2);

        //组织机构
        TabularDataVO tabularDataVO3 = new TabularDataVO();
        tabularDataVO3.setFirstName("组织机构/市区");
        ArrayList<TableBodyData> tableBodyDataList2 = new ArrayList<>();
        TableBodyData tableBodyData5 = new TableBodyData();
        TableBodyData tableBodyData6 = new TableBodyData();
        tableBodyData5.setName("济南路小学");
        tableBodyData6.setName("第二实验小学");

        List<String> data5 = new ArrayList<>();
        data5.add("37,031");
        data5.add("51.64%");
        List<String> data6 = new ArrayList<>();
        data6.add("37,03");
        data6.add("51.6%");
        tableBodyData5.setData(data5);
        tableBodyData6.setData(data6);
        tableBodyDataList2.add(tableBodyData5);
        tableBodyDataList2.add(tableBodyData6);
        tabularDataVO3.setTableBodyDataList(tableBodyDataList2);
        dataList.add(tabularDataVO3);

        tableVO.setValues(dataList);
        Document document = new Document();
        DocumentBuilder builder = new DocumentBuilder(document);
        // 添加表头并设置格式
        List<String> header = tableVO.getTitle();
        addTableHeader(builder, header);

        //设置表体的格式
        setTableBodyFormat(builder);
        // 根据集合循环添加数据行
        for (TabularDataVO collegeData : tableVO.getValues()) {
            addDataRow(builder, collegeData);
        }
        // 结束表格
        builder.endTable();
        //移动光标至末尾
        builder.moveToDocumentEnd();
        document.save("D:/saveFile/test/3333.docx");
    }
}
